package cn.itcalvin.sncoal.cth.utils;

import cn.hutool.json.JSONUtil;
import cn.itcalvin.sncoal.cth.config.CthConfig;
import cn.itcalvin.sncoal.cth.exception.AuthException;
import cn.itcalvin.sncoal.cth.pojo.common.RespUserInfo;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname JwtUtil
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/10/18 20:18
 * @Created by CALVIN
 */

public class JwtUtil {
    //过期时间设置为一天
    private static final long EXPIRE_TIME = CthConfig.EXPIRE;
    private static final String TOKEN_SECRET =CthConfig.SECRET;
    private static final String CLAIM_NAME =CthConfig.CLAIM_NAME;


    public JwtUtil() {
    }

    /**
     * 根据用户对象获取token
     *
     * @param respUserInfo
     * @return
     */
    public static String sign(RespUserInfo respUserInfo) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            Map<String, Object> header = new HashMap(2);
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            return JWT.create().withHeader(header).withClaim(CLAIM_NAME, JSONUtil.toJsonStr(respUserInfo)).withExpiresAt(date).sign(algorithm);
        } catch (Exception var4) {
            return null;
        }
    }

    /**
     * 校验token是否有效
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return (new Date()).before(jwt.getExpiresAt());
        } catch (Exception var4) {
            return false;
        }
    }


    /**
     * 刷新token，更新它的到期时间
     *
     * @param token
     * @return
     */
    public static String refresh(String token) {
        RespUserInfo userInfo = getUserInfo(token);
        return sign(userInfo);
    }


    /**
     * 根据token获取用户信息
     *
     * @param token
     * @return
     */
    public static RespUserInfo getUserInfo(String token) {
        try {
            if(!verify(token)){
                throw new AuthException("请重新登录");
            }
            DecodedJWT jwt = JWT.decode(token);
            String json = jwt.getClaim(CLAIM_NAME).asString();
            return JSONUtil.toBean(json, RespUserInfo.class);
        } catch (Exception var3) {
            throw new AuthException("请重新登录");
        }
    }

    public static RespUserInfo getUserInfo(){
        String token=getHeadToken();
        return getUserInfo(token);
    }


    public static String getHeadToken() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request1 = attributes.getRequest();
        String token = request1.getHeader("token");
        return token;
    }
}
